package com.algo.core.filter;

import com.algo.core.RequestContext;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 过滤器链
 */
public class RapidFilterChain {
    // 过滤器默认的容量大小
    private static final int DEFALUT_FILTER_CAPACITY = 16;

    private List<RapidFilter> rapidFilterList;

    private Map<RapidFilter, Integer> indexMap = new HashMap<>(DEFALUT_FILTER_CAPACITY);;

    private int rapidFilterCount = 0;

    public RapidFilterChain() throws Exception {
        // 加载过滤器
        rapidFilterList = RapidFilterLoader.load();

        // 排序
        Collections.sort(rapidFilterList, new Comparator<RapidFilter>() {
            @Override
            public int compare(RapidFilter o1, RapidFilter o2) {
                return o1.getOrder() - o2.getOrder();
            }
        });

        // 记录过滤器下标
        for (int i = 0; i < rapidFilterList.size(); i++) {
            indexMap.put(rapidFilterList.get(i), i);
            rapidFilterCount ++;
        }
    }

    /**
     * 执行过滤器逻辑
     * @param requestContext 请求上下文
     */
    public void doFilter(RequestContext requestContext) {
        this.doFilter(requestContext, null);
    }

    /**
     * 执行下一个过滤器逻辑
     * @param requestContext 请求上下文
     * @param rapidFilter 过滤器
     */
    public void doFilter(RequestContext requestContext, RapidFilter rapidFilter) {
        // 如果没有配置的过滤器，直接返回
        if (rapidFilterList == null || rapidFilterList.size() == 0) {
            return;
        }

        if (rapidFilter == null) {
            rapidFilterList.get(0).doFilter(requestContext, this);
            return;
        }

        // 根据下标，找到下一个过滤器，执行doFilter方法
        int nextIndex = indexMap.get(rapidFilter) + 1;
        if (nextIndex < rapidFilterCount) {
            rapidFilterList.get(nextIndex).doFilter(requestContext, this);
        }
    }

}
